﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JKF.BusinessLayer;
using JKF.BusinessLayer.BLL;
using SFWS.XHandler.Core;
using JKF.Substructure;
using SFWS.XJSON.Core;

namespace JKF.HandlerLayer.Sys
{
    public class LoginHandler : AHttpHandler
    {
        public override void ProcessRequest()
        {
            try
            {
                if (this.IsPostFor("Login"))
                {
                    this.Login();
                }
                else if (this.IsPostFor("GetProductRepairPeriod"))
                {
                    this.GetProductRepairPeriod();
                }
                else
                {
                    this.Response.Write("query");
                }
            }
            catch (Exception ex)
            {
                //将错误抛到客户端(以Json格式)
                //Utils.ToClient(true, ex.Message);
                this.ResponseJsonObject = new
                {
                    IsSucc = false,
                    Message = ex.Message
                };
                //写日志
                AppLogger.Log(ex.Message, ex);
            }
        }

        protected string ClientIP
        {
            get
            {

                string ip = "";
                if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null) // 服务器， using proxy
                {
                    //得到真实的客户端地址
                    ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); // Return real client IP.
                }
                else//如果没有使用代理服务器或者得不到客户端的ip not using proxy or can't get the Client IP
                {

                    //得到服务端的地址
                    ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString(); //While it can't get the Client IP, it will return proxy IP.
                }
                return ip;
            }
        }

        [Exp2Client]
        public void GetProductRepairPeriod()
        {
            bllSALES_CONTRACT salesContractMgr = new bllSALES_CONTRACT();
            
            try
            {
                var BAR_CODE = P("BAR_CODE");
                var CARD_NO = P("CARD_NO");

                Response.Write(new ResponseInf
                {
                    Success = true,
                    Data = (from a in salesContractMgr.GetProductRepairPeriod(BAR_CODE, CARD_NO).AsEnumerable()
                            select new
                            {
                                CARD_NO = a.Field<string>("CARD_NO"),
                                BAR_CODE = a.Field<string>("BAR_CODE"),
                                PRODUCT_NAME = a.Field<string>("PRODUCT_NAME"),
                                DATE_PURCHASE = a.Field<string>("DATE_PURCHASE"),
                                REPAIR_TERM = a.Field<Int32>("REPAIR_TERM").ToString(),
                                CLOSING_DATE = a.Field<string>("CLOSING_DATE"),
                                SHOP_NAME = a.Field<string>("SHOP_NAME")
                            }).ToList()
                }.ToJson());
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }

        }

        private void Login()
        {
            string sLoginName = Request["LoginName"].Trim();
            string sPassword = Request["Pwd"];
            string type = P("type");
            if (this.Session["IsLogined"] != null)
            {

                //如果 已经 登录&&就是当前用户,直接跳
                if (bllSYS_USER.CurrentUser != null && bllSYS_USER.CurrentUser.ACCOUNT == sLoginName)
                {
                    this.ResponseJsonObject = new
                    {
                        IsSucc = true,
                        Url = JKF.Substructure.SysConfig.DefalultUrl.Substring(2)
                    };
                }
                else
                { //如果 已经 登录&&不就是当前用户,禁止登录
                    this.ResponseJsonObject = new
                    {
                        IsSucc = false,
                        Message = "请开启另一个会话来登录!"
                    };
                }
                return;
            }

            bllSYS_USER sysUser = new bllSYS_USER();
            //参数是否正确
            if (Request["LoginName"] != null && Request["Pwd"] != null)
            {
                //用户名及密码是否为空
                if (sLoginName != string.Empty && sPassword != string.Empty)
                {
                    bool result = sysUser.LogIn(sLoginName, sPassword);

                    if (result)
                    {
                        BusinessBase.ClientIp =ClientIP;
                        this.Session["IsLogined"] = true;
                        this.ResponseJsonObject = new
                        {
                            IsSucc = true,
                            Message = string.Format("Welcome {0}.", this.F("LoginName")),
                            Url = JKF.Substructure.SysConfig.DefalultUrl.Substring(2)
                        };
                    }
                    else
                    {
                        this.ResponseJsonObject = new
                        {
                            IsSucc = false,
                            Message = "用户名或密码错误，请重试！"
                        };
                    }
                }
                else
                {
                    this.ResponseJsonObject = new
                    {
                        IsSucc = false,
                        Message = "用户名或密码不能为空！"
                    };
                }
            }
            else
            {
                //非法请求
                this.ResponseJsonObject = new
                {
                    IsSucc = false,
                    Message = "非法请求！"
                };
            }
        }
    }
}
